<template>
  <el-dialog
    title="创建审批单"
    width="600px"
    :before-close="handleClose"
    :visible="visible"
  >
    <el-form
      ref="createForm"
      :model="source"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="标题" prop="DocTitle">
        <el-input v-model="source.DocTitle" placeholder="标题" />
      </el-form-item>
    </el-form>
    <div slot="footer" style="text-align: center">
      <el-button :loading="loading" type="primary" @click="save">确定</el-button>
      <el-button @click="resetForm">重置</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { Create } from '@/flow/api/flowAppAudit'
import moment from 'moment'
import { Get } from '@/flow/api/flowApp'
export default {
  components: {
  },
  props: {
    appId: {
      type: String,
      default: null
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      source: {
        DocTitle: null
      },
      sourTitle: null,
      loading: false,
      rules: {
        DocTitle: [
          {
            required: true,
            message: '标题不能为空！',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    user() {
      return this.$store.getters.user
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.reset()
        }
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    handleClose() {
      this.$emit('update:visible', false)
    },
    resetForm() {
      this.source.DocTitle = this.sourTitle
    },
    save() {
      this.loading = true
      this.$refs['createForm'].validate((valid) => {
        if (valid) {
          this.createAudit()
        } else {
          this.loading = false
        }
      })
    },
    async createAudit() {
      try {
        const res = await Create({
          AppId: this.appId,
          DocTitle: this.source.DocTitle
        })
        this.$router.replace({ name: 'appAudit', params: { id: res.ItemId }})
        this.handleClose()
      } catch {
        this.loading = false
      }
    },
    formatTitle(title) {
      title = title.replace('{date}', moment().format('YYYYMMDD'))
      title = title.replace('{name}', this.user.name)
      title = title.replace('{unitDept}', this.user.unitDept)
      return title
    },
    async reset() {
      this.loading = false
      const res = await Get(this.appId)
      if (res.Status !== 1) {
        this.$message({
          type: 'error',
          message: '流程应用未启用!'
        })
        return
      }
      if (res.TitleTemplate != null) {
        res.TitleTemplate = this.formatTitle(res.TitleTemplate)
      }
      this.sourTitle = res.TitleTemplate
      this.source.DocTitle = res.TitleTemplate
    }
  }
}
</script>
